package com.spzx.product.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.spzx.common.core.web.controller.BaseController;
import com.spzx.common.core.web.domain.AjaxResult;
import com.spzx.common.core.web.page.TableDataInfo;
import com.spzx.product.domain.ProductUnit;
import com.spzx.product.service.ProductUnitService;
import io.swagger.v3.oas.annotations.Operation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * <p>
 * 商品单位 前端控制器
 * </p>
 *
 * @author atguigu
 * @since 2025-04-28
 */
@RestController
@RequestMapping("/productUnit")
public class ProductUnitController extends BaseController {


    @Autowired
    ProductUnitService productUnitService;

    @Operation(summary = "分页查询")
    @GetMapping("/list")
    public TableDataInfo selectproductlist(String name) {
        startPage();
        List<ProductUnit> list = productUnitService.selectproductuintlist(name);
        return getDataTable(list);
    }

    @Operation(summary = "显示商品单位详细信息")
    @GetMapping("/{id}")
    public AjaxResult getInfo(@PathVariable("id") Long id) {
        return success(productUnitService.getById(id));
    }

    @Operation(summary = "修改商品单位详细信息")
    @PutMapping
    public AjaxResult update(@RequestBody ProductUnit productUnit) {
        LambdaQueryWrapper<ProductUnit> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.eq(ProductUnit::getName, productUnit.getName());
        lambdaQueryWrapper.ne(ProductUnit::getId, productUnit.getId());
        if (productUnitService.count(lambdaQueryWrapper) > 0) {
            throw new RuntimeException("商品单位已存在");
        }
        boolean b = productUnitService.updateById(productUnit);
        return AjaxResult.success(b);
    }

    @Operation(summary = "新增商品单位")
    @PostMapping
    public AjaxResult add(@RequestBody ProductUnit productUnit) {
        LambdaQueryWrapper<ProductUnit> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.eq(ProductUnit::getName, productUnit.getName());
        if (productUnitService.count(lambdaQueryWrapper) > 0) {
            throw new RuntimeException("该单位已经存在");
        }
        productUnitService.save(productUnit);
        return AjaxResult.success();
    }

    @Operation(description = "删除商品单位")
    @DeleteMapping("/{ids}")
    public AjaxResult del(@PathVariable List<Long> ids){
        productUnitService.removeBatchByIds(ids);
        return AjaxResult.success();
    }


    @Operation(summary = "查询所有的商品的单位")
    @GetMapping("/getUnitAll")
    public AjaxResult list(){
        List<ProductUnit> list=productUnitService.list();
        return AjaxResult.success(list);
    }


}
